package greetings

import (
	"fmt"
	"sync"
	"time"
)

var x int32
var wg2 sync.WaitGroup
var lock sync.Mutex
var rwLock sync.RWMutex

func add() {

	// 互斥锁
	for i := 0; i < 5000; i++ {
		lock.Lock() // 加锁
		x = x + 1
		fmt.Println("x is :", x)
		lock.Unlock() // 解锁
	}
	wg2.Done()
}

func write() {
	rwLock.Lock()
	x++
	fmt.Println("rw lock write x is :", x)
	time.Sleep(5 * time.Millisecond)
	rwLock.Unlock()
}

func read() {
	rwLock.RLock()
	time.Sleep(time.Millisecond)
	rwLock.RUnlock()
}

// 读写锁
func LockDemo() {

	for i := 0; i < 5; i++ {
		go write()
	}
	for i := 0; i < 1000; i++ {
		go read()
	}
	time.Sleep(time.Second * 10)
}

// 普通的锁
func _() {

	wg2.Add(1)
	go add()
	go add()
	wg2.Add(1)
	wg2.Wait()
}

func _() {

	fmt.Println("test _")
}
